package Avocado.visual {

	import Avocado.util.MoveObject;
	
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	
	public class ExternalMovie extends MovieClip {
		
		private var url:String;
		private var assetLoader:MovieClip;
		
		public var target:MovieClip;
		
		private var loader:Loader;
		private var request:URLRequest;

		public function ExternalMovie(_url:String, _assetLoader:MovieClip=null) {
			super();
			this.addEventListener(Event.REMOVED_FROM_STAGE, removeThis);
			
			this.url = _url;
			this.assetLoader = _assetLoader;
			initThis();
		}
		
		private function initThis(e:Event=null):void{
			setupAssetLoader();
			setupTargetMovie();
		}
		
		private function removeThis(e:Event):void{
			this.removeEventListener(Event.REMOVED_FROM_STAGE, removeThis);
			loader.unload();
		}
		
		public function unloadSource():void{
			loader.unload();
		}
		
		
		
		
		private function setupAssetLoader():void{
			if (!this.assetLoader){
				this.assetLoader = new AssetLoader;
			}
			assetLoader.gotoAndPlay(1);
			addChild(assetLoader);
		}

		private function setupTargetMovie():void{
			request = new URLRequest(this.url);

			loader = new Loader;
			loader.load(request);
			loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loaderProgress);
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderComplete);
		}
		
		private function loaderProgress(e:ProgressEvent):void{
			var fact:Number = new Number(int(100*(e.bytesLoaded/e.bytesTotal)));
			assetLoader.gotoAndStop(fact);
		}
		
		private function loaderComplete(e:Event):void{
			loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, loaderComplete);
			target = MovieClip(loader.contentLoaderInfo.content);
			addChild(target);
			
			this.dispatchEvent(new Event(Event.COMPLETE));
		}

	}

}